//
//  ViewController.swift
//  TestInsatllFonts
//
//  Created by Burn on 2020/3/27.
//  Copyright © 2020 menksoft. All rights reserved.
//

//  https://stackoverflow.com/questions/57653398/ios-13-custom-fonts-download-and-installation
//  动态下载苹果提供的更多字体
//  https://juejin.im/post/5aebd428f265da0ba266d897

import UIKit

class ViewController: UIViewController {

    
    @IBOutlet weak var fontLabel: UILabel!
    @IBOutlet weak var progressView: UIProgressView!
    let fontName = "STXingkai-SC-Light"
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        
        
        let attributes = [kCTFontNameAttribute : fontName] as CFDictionary
        let fontDescription = CTFontDescriptorCreateWithAttributes(attributes)
        // create font font descriptor and add it in an array
        let descs = [fontDescription] as CFArray
        
        
        
        CTFontDescriptorMatchFontDescriptorsWithProgressHandler(descs, nil) { (state, progressParamater) -> Bool in
            let progressValue = (progressParamater as Dictionary)[kCTFontDescriptorMatchingPercentage]?.doubleValue

            switch state {
            case .didBegin: print("didBegin")
            case .didFinish:
                print("didFinish")
                
                CTFontManagerRegisterFontDescriptors(descs, .persistent, true) { (array, result) -> Bool in
                    
                    
                    print("array = \(array)");
                    
                    return true
                    
                }
                
                
                
            case .willBeginDownloading: print("willBeginDownloading")
            case .didFinishDownloading:
                print("--> download finish")
                DispatchQueue.main.async {
                    self.fontLabel.text = "download finish";
                    self.fontLabel.font = UIFont(name: self.fontName, size: 20)
                    
                    
                    
                    
                    
                }
            case .downloading:
                print("downloading#####\(progressValue ?? 0.0)")
                DispatchQueue.main.async {
                    self.progressView.progress = Float(progressValue! / 100.0 )
                }
            case .didFailWithError:
                if let error = (progressParamater as Dictionary)[kCTFontDescriptorMatchingError] as? NSError {
                    print(error.description)
                } else {
                    print("ERROR MESSAGE IS NOT AVAILABLE")
                }

            default: print(String(reflecting: state))
            }

            return true

        }
        
        
        
    }

    
    
}

